package leetcode

import kotlinetc.println
import sun.nio.cs.ext.MacHebrew

//https://leetcode.com/problems/powx-n/

fun main(args: Array<String>) {

    (1 / 6.25).println()
    myPow1(2.00000, 10).println()
}


fun myPow(x: Double, n: Int): Double {


    if (n == Int.MIN_VALUE && x > 1) return 0.00

    if (n == Int.MAX_VALUE && Math.abs(x) < 1) return 0.00

    if (Math.abs(x) == 1.0) return if (x < 0 && Math.abs(n) % 2 != 0) -1.0 else 1.0

    if (x == 0.00) return x

    if (n == 0) return 1.0

    if (n == 1) return x

//  if (n == -1) return 1 / x


//stackoverflow for case   1.00001 123456

//    if (n < 0)
//        return 1 / x * myPow(1 / x, Math.abs(n) - 1)
//    else return x * myPow(x, Math.abs(n) - 1)

    var r = x

    val exp = Math.abs(n)

    if (n < 0) r = 1 / r



    if (n % 2 == 0) return myPow(r, exp / 2) * myPow(r, exp / 2)
    else return r * myPow(r, exp - 1)

}


fun myPow1(x: Double, n: Int): Double {
    if (n == 0) return 1.0
    val half = myPow(x, n / 2)
    if (n % 2 == 0) return half * half
    return if (n > 0) half * half * x else half * half / x
}